'use strict'

const asyncValidate = require('async-validator')

module.exports = {
  login() {
    if (!this.user || !this.user._id) {
      this.throw(401, 'not login', '请登陆后再操作')
    }
  },
  admin() {
    if (!this.user || !this.user._id) {
      this.throw(401, 'not login', '请登陆后再操作')
    }
    if (!this.user || !this.user.is_admin) {
      this.throw(403, 'not login', '无权操作')
    }
  },
  validate(rules, model, attributes) {
    // 获取当前的校验模型
    if (!rules) {
      throw new Error('校验模型不存在')
    }
    if (typeof model === 'string') {
      attributes = model
      model = this.request.body
    }
    // 校验对象空则为 body
    model = model || this.request.body
    // 删除或选取某些值
    if (attributes) {
      if (attributes.includes('-')) { // 只删除
        attributes.split(/[, ]/).forEach(key => {
          if (key.startsWith('-')) {
            delete model[key.replace('-', '')]
          }
        })
      } else { // 只选取
        attributes = attributes.split(/[, ]/)
        const data = {}
        attributes.forEach(key => {
          data[key] = model[key]
        })
        model = data
      }
    }
    // 选取需要验证的 key 验证
    return new Promise(resolve => {
      new asyncValidate(rules).validate(model, { first: true }, errors => {
        if (errors) {
          this.throw(422, 'not validate', { message: errors[0].message, errors })
        }
        resolve(model)
      })
    })
  },
}
